#include "FtpClient.h"

FtpClient::FtpClient(QObject *parent) :
    QObject(parent), qFtpClient(0), ready(false)
{
}

void FtpClient::setHost(const QString &host)
{
    qUrl.setHost(host);
}

void FtpClient::setUserName(const QString &userName)
{
    qUrl.setUserName(userName);
}

void FtpClient::setPassword(const QString &password)
{
    qUrl.setPassword(password);
}

void FtpClient::setPath(const QString &path)
{
    qUrl.setPath(path);
}

void FtpClient::setFilename(const QString &name)
{
    fileName    = name;
    ready       = true;
}

void FtpClient::startUpload()
{
    qDebug() << QDateTime::currentDateTime().toString("HH:mm:ss") << "startUpload";
    connectToServer();
}

void FtpClient::ftpCommandFinished(int /*commandId*/, bool error)
{
//    qDebug() << "ftpCommandFinished";
    if (qFtpClient->currentCommand() == QFtp::ConnectToHost)
    {
        if ( !error )
        {
            qDebug() << QDateTime::currentDateTime().toString("HH:mm:ss") << "QFtp::ConnectToHost Ok !!!";
        }
        else
        {
            qDebug() << QDateTime::currentDateTime().toString("HH:mm:ss") << "QFtp::ConnectToHost error !!!";
        }
    }

    if (qFtpClient->currentCommand() == QFtp::Login)
    {
        if (!error)
        {
            qDebug() << "login ok";
            uploadFileToServer();
        }
        else
        {
            qDebug() << "error login !!!";
        }
    }

    if (qFtpClient->currentCommand() == QFtp::Put)
    {
        if (error)
        {
            qDebug() << "file put error";
        }
        else
        {
            qDebug() << "upload ok";
            emit finishedUpload(false);
        }
    }
}

void FtpClient::connectToServer()
{
    if (qFtpClient) {
        qFtpClient->abort();
        qFtpClient->deleteLater();
        qFtpClient = 0;
    }

    qFtpClient = new QFtp(this);
    connect(qFtpClient, SIGNAL(commandFinished(int,bool)), this, SLOT(ftpCommandFinished(int,bool)));

    qDebug() << "url.host():" << qUrl.host();
    qFtpClient->connectToHost(qUrl.host(), qUrl.port(21));

    if (!qUrl.userName().isEmpty())
    {
        qDebug() << "url.userName():" << qUrl.userName();
//        qDebug() << "url.password():" << qUrl.password();
        qFtpClient->login(QUrl::fromPercentEncoding(qUrl.userName().toLatin1()), qUrl.password());
    }
    if (!qUrl.path().isEmpty())
    {
        qDebug() << "url.path():" << qUrl.path();
        qFtpClient->cd(qUrl.path());
    }
}

void FtpClient::uploadFileToServer()
{
    qDebug() << "upload";
    if (!ready)
    {
        qDebug() << "Not set pdf file name";
        return;
    }
//    QString
    QString homeFile = QDir::homePath() + QDir::separator() + "PDF" + QDir::separator() + fileName;
    qFtpClient->put(new QFile(homeFile), fileName);
    qDebug() << "finish";
}
